package com.kefu.chat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kefu.chat.model.ChatChannel;
import com.kefu.chat.service.ChatChannelService;
import com.kefu.chat.service.ChatWxWorkService;
import com.kefu.common.controller.AbstractBaseController;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@RestController
@RequestMapping("chat/wxwork/{appId}")
public class ChatWxWorkController extends AbstractBaseController {

    @Autowired
    private ChatWxWorkService chatWxWorkService;
    @Autowired
    private ChatChannelService chatChannelService;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appId, String msg_signature, String timestamp, String nonce, String echostr) {
        logger.info("接收到来自企业微信的认证消息：[{},{}, {}, {}, {}]", appId, msg_signature, timestamp, nonce, echostr);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
        WxCpService wxCpService = chatWxWorkService.getWxCpService(appId);
        if (wxCpService.checkSignature(msg_signature, timestamp, nonce, echostr)) {
            return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
        }
        return null;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId, @RequestBody String requestBody, String msg_signature, String timestamp, String nonce) {
        logger.info("接收企业微信请求：{},{},{},{},{}", appId, msg_signature, timestamp, nonce, requestBody);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
        WxCpService wxCpService = chatWxWorkService.getWxCpService(appId);
        WxCpXmlOutMessage outMessage = null;
        String result = null;
        WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(requestBody, wxCpService.getWxCpConfigStorage(),
                timestamp, nonce, msg_signature);
        logger.info("接收企业微信请求解密:{},{}", appId, inMessage);
        if (inMessage != null) {
            if (inMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
                outMessage = chatWxWorkService.eventHandle(appId, inMessage);
            } else {
                outMessage = chatWxWorkService.msgHandle(appId, inMessage);
            }
        }
        if(outMessage!=null){
            result = outMessage.toEncryptedXml(wxCpService.getWxCpConfigStorage());
        }
        logger.info("企业微信组装回复信息：{}", result);
        return result;
    }

}

